//
//  HNHomeDetialViewController.m
//  HappyNews
//
//  Created by baiping on 16/1/13.
//  Copyright © 2016年 BPWBANP. All rights reserved.
//

#import "HNHomeDetialViewController.h"
#import "HNHomeTabBarView.h"
#import "HNHomeDetialModel.h"
#import "HNHomeTarBarModel.h"
#import "HNShareView.h"

@interface HNHomeDetialViewController ()<UIWebViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) NSDictionary *dataDic;

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) HNHomeTabBarView *tabBarView;

@property (nonatomic, strong) UIImageView *titleIcon;

@property (nonatomic, strong) HNHomeDetialModel *model;

@property (nonatomic, strong) UILabel *subTitle;

@property (nonatomic, strong) UIView *headView;

@property (nonatomic, strong) UISwipeGestureRecognizer *swipeLeftGesture;

@property (nonatomic, strong) UISwipeGestureRecognizer *swipeRigthGesture;

@property (nonatomic, strong) UIView *stausBarview;

@property (nonatomic, strong) NSDictionary *tarBarDataDic;

@property (nonatomic, strong) HNHomeTarBarModel *tarBarModel;

@property (nonatomic, strong) UIImageView *burfImageView;

// 添加分享视图 已经上面按钮的方法
@property HNShareView *shareView;

// 添加一个属性用于记录点赞数 (点一下点赞按钮点赞数+1)
@property (nonatomic, assign) NSInteger voteNumber;

@end

@implementation HNHomeDetialViewController


- (NSDictionary *)tarBarDataDic{
    
    if (!_tarBarDataDic) {
        
        _tarBarDataDic = [NSDictionary dictionary];
        
    }
    return _tarBarDataDic;

}
- (NSDictionary *)dataDic{
    
    if (!_dataDic) {
        
        _dataDic = [NSDictionary dictionary];
        
    }
    return _dataDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
   // 加载数据源数据
    [self loadRequsst];
    
    // 加载子控件
    [self addSubviews];

    // 添加自定义tabBarView;
    
    [self addTabBarView];
  
    // 加载tabBarView上面的信息
    [self addTabBarData];
    
    // 注册通知
    //  获取通知中心(单例)
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //  注册 并实现接到消息后的方法
    //  通知的名字 有规范: 一般 全部大写
    //  可以使用宏定义 写到全局头文件里
    [center addObserver:self selector:@selector(notification:) name:@"NIGHT" object:nil];


}

//  实现接到通知的方法
//  通知是通知中心发的 你接到是一个通知 而不是 通知中心
#pragma mark 改变皮肤的通知
- (void)notification:(NSNotification *)notification{

   
    
    
    
}


// 请求数据源数据
- (void)loadRequsst{
    
    NSString *urlStr = [NSString stringWithFormat:@"http://news-at.zhihu.com/api/4/story/%@", _idArray[_currentIndex]];
   // NSLog(@"%@", _number);
    
    [HNRequestManager requestWithUrlString:urlStr parDic:nil method:GET finish:^(NSData *data) {
        
        _dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        _model = [[HNHomeDetialModel alloc]init];
        
        [_model setValuesForKeysWithDictionary:_dataDic];
        
        // 加载webView 和 图片数据
        [self loadData];
    
    } error:^(NSError *error) {
        
        [MBProgressHUD showError:@"加载失败"];
        
    }];
}
- (void)addSubviews{
    
    // 打开导航控制器
    self.navigationController.navigationBar.hidden = YES;
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    
    _scrollView.backgroundColor = [UIColor whiteColor];

    _scrollView.bounces = YES;
    
    _scrollView.alwaysBounceHorizontal = NO;
    
    _scrollView.alwaysBounceVertical = YES;
    
    _scrollView.delegate = self;
    
    [self.view addSubview:_scrollView];
    
    [self addWebView];
    
    [self addHeadViewAndSubViews];
    
    // 添加平移手势
    
    [self addGestureRecognizer];
    
}

- (void)addWebView{
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    
    _webView.delegate = self;
    
    [_scrollView addSubview:_webView];
}

- (void)addHeadViewAndSubViews{
    
    _titleIcon = [[UIImageView alloc]init];
    
    _titleIcon.frame = CGRectMake(0, 0, kScreenWidth, 220);
    
    [_scrollView addSubview:_titleIcon];
    
    _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 220)];
    
    _headView.alpha = 0.7;
    
    [_scrollView addSubview:_headView];
    
    _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 140, kScreenWidth - 40, 70)];
    
    _titleLabel.numberOfLines = -1;
    
    _titleLabel.textColor = [UIColor whiteColor];
    
    _titleLabel.font = [UIFont boldSystemFontOfSize:20];
    
    [_headView addSubview:_titleLabel];
    
    _subTitle = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth - 150, 190, 120, 20)];
    
    [_headView addSubview:_subTitle];
    
    _subTitle.font = [UIFont systemFontOfSize:8];
    
    _subTitle.textColor = [UIColor whiteColor];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y <= 0) {
        
        CGRect newHeadFrame = _headView.frame;
        
        newHeadFrame.size.height -= scrollView.contentOffset.y * 0.05;
        
        newHeadFrame.origin.y = scrollView.contentOffset.y * 0.9;
        
        _headView.frame = newHeadFrame;
        
        CGRect newIconFrame = _titleIcon.frame;
        
        newIconFrame.size.height -= scrollView.contentOffset.y * 0.015;
        
        newIconFrame.origin.y = scrollView.contentOffset.y ;
        
        _titleIcon.frame = newIconFrame;
        
        
    
    }
    
    if (scrollView.contentOffset.y >= 220) {
    
        if (!_stausBarview) {
            
            _stausBarview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
            
            _stausBarview.backgroundColor = [UIColor whiteColor];
            
            [self.view addSubview:_stausBarview];
        }
        
    }else{
        
        if (_stausBarview) {
            
        [_stausBarview removeFromSuperview];
            
        _stausBarview = nil;
            
        
        }
    }

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    // 解决上面有图片不能去除bug
    CGRect newHeadFrame = _headView.frame;
    
    newHeadFrame.size.height = 220;
    
    CGRect newIconFrame = _titleIcon.frame;
    
    newIconFrame.size.height = 220;

    [UIView animateWithDuration:0.5f animations:^{
        
        _headView.frame = newHeadFrame;
        
        _titleIcon.frame = newIconFrame;
        
    }];
}

- (void)loadData{
    
  NSString *webStr = [NSString stringWithFormat:@"<html><head><link rel=\"stylesheet\" href=%@></head><body>%@</body></html>",_model.css[0], _model.body];
      
      // <section><img src=\"http://img1.gtimg.com/12/1224/122455/12245555_980x1200_0.jpg\"</section>
 // NSString * newStr = [NSString stringWithFormat:@"<head><style>img{width:320px !important;}</style></head>%@", webStr];
    
      [self.webView loadHTMLString:webStr baseURL:nil];
    
    _titleLabel.text = _model.title;
    
    [_titleIcon sd_setImageWithURL:[NSURL URLWithString:_model.image]];
    
    _subTitle.text = [NSString stringWithFormat:@"图片:%@", _model.image_source];

    // sublabel 自适应宽度
    CGSize size = [_subTitle.text sizeWithFont:[UIFont systemFontOfSize:8] constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
                   
    _subTitle.frame = CGRectMake(kScreenWidth - 10 - size.width, 190, size.width, 20);

    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    NSLog(@"加载了数据");
    
    CGFloat height = webView.scrollView.contentSize.height;
    
    CGRect newFrame = webView.frame;
    
       newFrame.size.height = height;
    
        webView.frame = newFrame;

    NSLog(@"%f", height);
    
    _scrollView.contentSize = CGSizeMake(kScreenWidth, height + 30);
    
    // 为了解决用户在下面的webview下面轻扫 由于没有刷新scrollview的位置导致scrollview的滚动范围到过height 可以没有手动刷新用户当前的位置
    _scrollView.contentOffset = CGPointMake(0, 0);
    
}

- (void)addGestureRecognizer{
    
    // 添加左扫方法
    _swipeLeftGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGestureAction:)];
    
    _swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    
    [self.webView addGestureRecognizer:_swipeLeftGesture];
    
  // 添加右扫方法
    
    _swipeRigthGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeRigthGesture:)];
    
    _swipeRigthGesture.direction = UISwipeGestureRecognizerDirectionRight;
    
    [self.webView addGestureRecognizer:_swipeRigthGesture];

}
// 实现左扫手势
- (void)swipeGestureAction:(UIGestureRecognizer *)sender{
    
            _currentIndex++;
    
    if (_currentIndex < _idArray.count) {
        
        [_scrollView removeFromSuperview];
        
        _scrollView = nil;
        
        [self loadRequsst];
        
        [self addSubviews];

        // 点击退出后跳转到setting界面 使用转场动画
        //定义个转场动画
        CATransition *animation = [CATransition animation];
        //转场动画持续时间
        animation.duration = 0.5f;
        //计时函数，从头到尾的流畅度？？？
        animation.timingFunction=UIViewAnimationCurveEaseInOut;
        //转场动画类型 翻页效果
        animation.type = @"pageCurl";
        //转场动画将去的方向
        animation.subtype = kCATransitionFromRight;
        //动画时你需要的实现
        [self.view.layer addAnimation:animation forKey:@"leftAnimatiom"];

    }else{
        
        [MBProgressHUD showError:@"亲, 已经是最后一篇了!"];
        
        _currentIndex = _idArray.count - 1;
        
    }
}

// 实现右扫方法
- (void)swipeRigthGesture:(UIGestureRecognizer *)sender{
    
 
    _currentIndex--;
    
    if (_currentIndex >= 0) {
        
        [_scrollView removeFromSuperview];
        
        _scrollView = nil;
        
        [self loadRequsst];
        
        [self addSubviews];
        
        // 点击退出后跳转到setting界面 使用转场动画
        //定义个转场动画
        CATransition *animation = [CATransition animation];
        //转场动画持续时间
        animation.duration = 0.5f;
        //计时函数，从头到尾的流畅
        animation.timingFunction=UIViewAnimationCurveEaseInOut;
        //转场动画类型 翻页效果
        animation.type = @"pageCurl";
        //转场动画将去的方向
        animation.subtype = kCATransitionFromLeft;
        //动画时你需要的实现
        [self.view.layer addAnimation:animation forKey:@"rigthAnimatiom"];
        
        
        
        
    }else{
        
        [MBProgressHUD showError:@"亲, 没有上一篇了!"];
        
        _currentIndex = 0;
        
    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addTabBarView{
    
    _tabBarView = [[HNHomeTabBarView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    self.tabBarView.backgroundColor = [UIColor whiteColor];
    
    [self.tabBarController.tabBar addSubview:_tabBarView];
    
    // 给tabBar上的按钮添加点击方法
    
    [_tabBarView.backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
     [_tabBarView.nextBtn addTarget:self action:@selector(nextBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
     [_tabBarView.thumbBtn addTarget:self action:@selector(thumbBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
     [_tabBarView.shareBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
     [_tabBarView.messageBtn addTarget:self action:@selector(messageBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

// 加载tabBarData
- (void)addTabBarData{
    
    // http://news-at.zhihu.com/api/4/story-extra/7744951
    
    NSString *urlStr = [NSString stringWithFormat:@"http://news-at.zhihu.com/api/4/story-extra/%@", _number];
    
    
    [HNRequestManager requestWithUrlString:urlStr parDic:nil method:GET finish:^(NSData *data) {
        NSLog(@"%@", urlStr);
        
        self.tarBarDataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        _tarBarModel = [[HNHomeTarBarModel alloc]init];
        
        [_tarBarModel setValuesForKeysWithDictionary:_tarBarDataDic];
        
        // 不用像tableView 那样reloaddata(刷新方法为代理方法) 可以直接在这里刷新控件
    
        _tabBarView.messageNumberLabel.text = [NSString stringWithFormat:@"%ld", _tarBarModel.comments];
        
        // 记录初始点赞数
        _voteNumber = _tarBarModel.popularity;
        
    } error:^(NSError *error) {
        
       [MBProgressHUD showError:@"加载失败"];
        
        
    }];
    

}
- (void)backBtnAction:(UIButton *)sender{
    
    self.navigationController.navigationBar.hidden = YES;
    
    [_tabBarView removeFromSuperview];
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)nextBtnAction:(UIButton *)sender{
    
    [self swipeGestureAction:nil];
    
    
}

- (void)thumbBtnAction:(UIButton *)sender{
    
    _tabBarView.thumbNumberLabel.text = [NSString stringWithFormat:@"%ld", (long)_tarBarModel.popularity];
    
    _tabBarView.thumbNumberLabel.textColor = HNBgColor;
    
    /*********************给点赞添加动画效果****************************/
    [UIView beginAnimations:@"bigAnimatiom" context:nil];
    
    [UIView setAnimationDuration:0.5];
    
    [_tabBarView.thumbBtn setImage:[UIImage imageNamed:@"News_Navigation_Voted"] forState:(UIControlStateNormal)];
    
     _tabBarView.addNumberLabel.alpha = 1;
    
    _tabBarView.thumbBtn.imageView.transform = CGAffineTransformMakeScale(1.5, 1.5);
    
   // _tabBarView.thumbBtn.imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView commitAnimations];
    
    [UIView beginAnimations:@"Animatiom" context:nil];
    
    [UIView setAnimationDuration:0.5];
    
    [_tabBarView.thumbBtn setImage:[UIImage imageNamed:@"News_Navigation_Voted"] forState:(UIControlStateNormal)];
    
   // _tabBarView.thumbBtn.imageView.transform = CGAffineTransformMakeScale(1.5, 1.5);
    
     _tabBarView.thumbBtn.imageView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    
    _tabBarView.addNumberLabel.alpha = 0;
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView commitAnimations];
    
    /*********************动画效果结束****************************/
    
    // 增加点赞数
    _tabBarView.thumbNumberLabel.text = [NSString stringWithFormat:@"%ld", _voteNumber++];
    
    // 让按钮失效
    _tabBarView.thumbBtn.enabled = NO;
    
}

#pragma mark ---- 实现分享
- (void)shareBtnAction:(UIButton *)sender{
    
    
  
      self.tabBarController.tabBar.hidden = YES;
    
        // 改变视图位置 并且实现毛玻璃效果
        /**
         1. 截取当前屏幕
         2. 创建一个imageView和毛玻璃类 然后把这个
         */
        UIGraphicsBeginImageContext(self.view.bounds.size);     //currentView 当前的view  创建一个基于位图的图形上下文并指定大小为
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];//renderInContext呈现接受者及其子范围到指定的上下文 进栈
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();//返回一个基于当前图形上下文的图片
        UIGraphicsEndImageContext();//移除栈顶的基于当前位图的图形上下文
        // 栈就是
        UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);//然后将该图片存到图片图
        
        // 常见毛玻璃类
        UIBlurEffect *blurEff = [UIBlurEffect effectWithStyle:(UIBlurEffectStyleDark)];
        // 创建显示的毛玻璃类
        UIVisualEffectView *visualEffV = [[UIVisualEffectView alloc]initWithEffect:blurEff];
        visualEffV.frame = self.view.bounds;
        visualEffV.alpha = 0.5;
        
        if (!_burfImageView) {
           
            _burfImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
            
            // 添加毛玻璃效果
            [_burfImageView addSubview:visualEffV];
            
            _burfImageView.image = viewImage;
            
            [self.view addSubview:self.burfImageView];
            
            // 弹出分享按钮视图
            if (!_shareView) {
                
        _shareView = [[HNShareView alloc]initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 350)];
                
        [self.view addSubview:_shareView];
                
        _shareView.backgroundColor = [UIColor colorWithRed:228.0 / 256 green:228.0 / 256 blue:228.0 / 256 alpha:1];
           
        // 给取消按钮添加返回方法
        [_shareView.cancelBtn addTarget:self action:@selector(cancelBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
                
            }
            
        }
        
        [UIView animateWithDuration:0.8 animations:^{
            
        //  动画效果
            
        _shareView.frame =  CGRectMake(0, kScreenHeight -  350, kScreenWidth, 350);;
            
        }];
        
 
}

// 实现分享取消按钮的方法
- (void)cancelBtnAction:(UIButton *)sender{
    
    if (_burfImageView) {
        
        [_burfImageView removeFromSuperview];
        
        _burfImageView = nil;
    }
    
    if (_shareView){
        
        [UIView animateWithDuration:0.8 animations:^{
           
            //  动画效果
   _shareView.frame =  CGRectMake(0, kScreenHeight - 44, kScreenWidth, 350);;
       
        } completion:^(BOOL finished) {
            
             self.tabBarController.tabBar.hidden = NO;
            
            [UIView animateWithDuration:0.2 animations:^{
                
                _shareView.frame =  CGRectMake(0, kScreenHeight , kScreenWidth, 350);
                
            } completion:^(BOOL finished) {
                
                [self.shareView removeFromSuperview];
                
                self.shareView = nil;
                
            }];
        }];
 
    }
}
- (void)messageBtnAction:(UIButton *)sender{
    
    
    
    
}

@end
